package com.hxm.servicebroadcasttest;

import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String TAG = "Test";
    private Button start, stop, bind, unBind;
    private Intent intent;
    private LalaBroadcastReceiver receiver;
    private HahaService.MyBinder binder;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "onServiceConnected: is connected");
            binder = (HahaService.MyBinder) service;
            binder.showToast();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "onServiceDisconnected: is disconnected");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start = (Button) findViewById(R.id.btn_start_service);
        stop = (Button) findViewById(R.id.btn_stop_service);
        bind = (Button) findViewById(R.id.btn_bind_service);
        unBind = (Button) findViewById(R.id.btn_unbind_service);

        start.setOnClickListener(this);
        stop.setOnClickListener(this);
        bind.setOnClickListener(this);
        unBind.setOnClickListener(this);

        receiver = new LalaBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.hxm.ACTION_ONE");
        filter.addAction("com.hxm.ACTION_TWO");
        filter.addAction("com.hxm.ACTION_THREE");
        registerReceiver(receiver, filter);

        intent = new Intent(this, HahaService.class);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        unbindService(conn);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start_service:
                startService(intent);
                break;
            case R.id.btn_stop_service:
                stopService(intent);
                break;
            case R.id.btn_bind_service:
                bindService(intent, conn, BIND_AUTO_CREATE);
                break;
            case R.id.btn_unbind_service:
                unbindService(conn);
                break;
        }
    }
}
